import axios from 'axios';
import { fromJS } from 'immutable';

export const searchFocusAction = focused => ({
    type: 'SEARCH_FOCUS',
    focused,
});

export const mouseEnterAction = mouseIn => ({
    type: 'MOUSE_ENTER',
    mouseIn,
});

export const changePageAction = page => ({
    type: 'CHANGE_PAGE',
    page,
});

export const searchValueAction = value => ({
    type: 'SEARCH_VALUE',
    value,
});

const initListAction = list => ({
    type: 'INIT_LIST',
    list: fromJS(list), // immutable对象
    totalPage: Math.ceil(list.length / 10),
});

// 使用redux-thunk后，action可以返回函数，用于进行异步请求(axios)
export const getListAction = () => {
    return dispatch => {
        let list = [];
        axios
            .get('https://www.fastmock.site/mock/0764b93cba70add273910b232c51aad8/development/api/getHotList')
            .then(res => {
                if (res.data.data.length > 0) {
                    for (const val of res.data.data) {
                        list.push(val.name);
                    }
                }
                const action = initListAction(list);
                dispatch(action); // 将action传给store
            })
            .catch(error => {
                console.log(error);
            });
    };
};
